from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from Acquisition import aq_inner
from zope.component import getMultiAdapter
from zope.i18n.interfaces import ITranslationDomain
from zope.component import queryUtility
from zope.component import getUtility
from Products.CMFCore.interfaces import ISiteRoot

from my315ok.fangcan import fangcanMessageFactory as _
from my315ok.fangcan.config import PACKAGE_HOME

from my315ok.fangcan.interfaces import Isecondhandfolder
import os
from Products.CMFPlone.utils import _createObjectByType

from my315ok.fangcan.content.vocabulary import area_terms,bigarea_terms,biztype_terms


class IpostdataView(Interface):
    """
    postdata view interface
    """

    def receive():
        """ receive post data"""
    def update():
        """ update recorder"""
    def create():
        """ create new recorder"""
 


class postdataView(BrowserView):
    """
    postdata browser view
    """
    implements(IpostdataView)
    validfields = ["House_direction",
                   "Create_time",
                   "Rent_unitprice",
                   "Sellingprice",
                   "Curr_state",
                   "Decorate",
                   "Overday"                   
                   ]

    def __init__(self, context, request):
        self.context = context
        self.request = request
        
    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()
    
    def portal_state(self):
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        return portal_state
    
    def valided(self):
#        import pdb
#        pdb.set_trace()
        if self.request["REQUEST_METHOD"] == "POST":
            return True
        else:
            return False
    def update(self):
#        import pdb
#        pdb.set_trace()
        if not self.valided():
            return _(u"invalid request")
        else:
            data = self.receive()
            id = data["house_no"]
            if len(id) <  1:
                return _(u"these dada is not enough")
            
            return self.create(id,data) 
            
    
            
            
           
    def loadImage(self,name, size=0):
        """Load image from testing directory
        """
        path = os.path.join(PACKAGE_HOME,'browser',name)
        fd = open(path, 'rb')
        data = fd.read()
        fd.close()
        return data
    def receive(self):
#        import pdb
#        pdb.set_trace()
        data = self.request.form
        for paremeter  in data.keys() :
            if data[paremeter] =="" or len(data[paremeter]) ==0:
                data.pop(paremeter)
#            if data[j] not in validfields:
#                data.pop(j)                
        return data
        

    def strtotime(self,instr):
        import time
        fmt0 = '%Y-%m-%d %H:%M:%S'
        fmt2 = '%Y-%m-%d'
#        fmt3 = '%Y-%m-%d %H:%M:%S'
        from time import mktime,strptime
        from datetime import datetime
        try:
            t2 =strptime(instr,fmt2)
        except:
            t2 = strptime(instr,fmt0)
            
        t3 = datetime.fromtimestamp(mktime(t2))
        t3 = t3.strftime(fmt2)
        return t3
        
        
    def strippointer(self,instring):
        res = instring.split('.')
        return res[0]
#        
#    def container(self):
##        import pdb
##        pdb.set_trace()
#        target = "secondhand"
#        portal = self.portal_state().portal()
#        container = portal.unrestrictedTraverse(target, default=None)
#        return container     
    def container(self):
#        import pdb
#        pdb.set_trace()        
        portal = getUtility(ISiteRoot)
        pc = getToolByName(portal, 'portal_catalog')
        brains = pc(object_provides=Isecondhandfolder.__identifier__)
        target = brains[0].id
        portal = self.portal_state().portal()
        container = portal.unrestrictedTraverse(target, default=None)
        return container
       


    def backward_translate(self,item,vocabulary):
#        import pdb
#        pdb.set_trace()
        util = queryUtility(ITranslationDomain, 'my315ok.fangcan')
        for term in vocabulary:                               
            tted = util.translate(term.title,target_language="zh",default="yuhu")
            if isinstance(tted,unicode):
                tted = tted.encode('utf-8')            
            if tted ==item:
                return term.value
            else:
                continue                     
        
        return item
        
    def setposition(self,obj,area):
        """"""
        position = {"yuhu":(27.860416,112.907467),'yuetang':(27.887821,112.971611),'jiuhua':(27.917464,112.940769),'yisuhe':(27.776413,112.955904)}
        if area in position.keys():
            pset = position[area]
            obj.setLongitude(pset[1])
            obj.setLatitude(pset[0])
            
            
 
        
    def create(self,id,data):
#        import pdb
#        pdb.set_trace()
        if hasattr(self.context.acl_users.session, 'setupSession'):
                # Plone 3
            self.context.acl_users.session.setupSession("admin", self.context.REQUEST.RESPONSE)
        else:
                # Plone 4
            self.context.acl_users.session._setupSession("admin", self.context.REQUEST.RESPONSE)

#        import pdb
#        pdb.set_trace()
#        contn = self.container()
        folder = self.container()
        if id in folder.objectIds():
            house = getattr(folder, id, None)
            msg = _(u"data update is successful")
        else:
            msg = _(u"data had imported successfully")
            _createObjectByType("house", folder, id)
#            folder.invokeFactory("house", id)
            house = getattr(folder, id, None)
#            try:
#                watermark = self.loadImage("fcwatermark.jpg")
#                house.setImage(watermark,content_type="image/jpg",filename='fcwatermaik.jpg')
#            except:
#                pass
#            try:
#                wftool = getToolByName(house, 'portal_workflow')
#                wftool.doActionFor(house, action='publish')
#            except:
#                pass          
        
        
        m = data.keys()
        if "house_direction" in m:            
            house.setHouse_direction(data["house_direction"])
        if "create_time" in m:
            ltime = self.strippointer(data["create_time"])
            out = self.strtotime(ltime)            
            house.setCreate_time(out)
        if "rent_unitprice" in m:            
            house.setRent_unitprice(data["rent_unitprice"])
        if "sellingprice" in m:
            price = data["sellingprice"]
            if len(price) ==0:
                price = 3000           
            house.setSellingprice(price)
        if "curr_state" in m:            
            house.setCurr_state(data["curr_state"])
        if "decorate" in m:            
            house.setDecorate(data["decorate"])
        if "overday" in m:
            out = self.strtotime(data["overday"])                               
            house.setOverday(out)
        if "record_no" in m:            
            house.setRecord_no(data["record_no"])
        if "level" in m:            
            house.setLevel(data["level"])
        if "use" in m:            
            house.setUse(data["use"])
        if "owner_name" in m:            
            house.setOwner_name(data["owner_name"])
        if "lastfollow_time" in m:
            ltime = self.strippointer(data["lastfollow_time"])
            
            out = self.strtotime(ltime)           
            house.setLastfollow_time(out)
        if "house_no" in m:
            hid =  data["house_no"]           
            house.setHouse_no(hid)
#            house.setTitle(hid)
        if "area" in m:            
#            house.setArea(data["area"])
            tmp = data["area"]
            if isinstance(tmp,str):                                              
                tmp = self.backward_translate(tmp, area_terms)                                        
            house.setArea(tmp)
            self.setposition(house,tmp)
            del tmp             
            
            
        if "commission_no" in m:            
            house.setCommission_no(data["commission_no"])
        if "country" in m:            
            house.setCountry(data["country"])
        if "biztype" in m:
            tmp1 = data["biztype"]
            house.setTitle(tmp1)
            if isinstance(tmp1,str):                                              
                tmp = self.backward_translate(tmp1, biztype_terms)
#            if tmp =="":
#                house.setTitle(tmp1)
                
            house.setCategory(tmp)                        
            house.setBiztype(tmp)
            del tmp,tmp1           
            
        if "mianji" in m: 
            mianji = data["mianji"]
            mianji = self.strippointer(mianji)          
            house.setMianji(mianji)
            del mianji
        if "estate_type" in m:            
            house.setEstate_type(data["estate_type"])
        if "card_no" in m:            
            house.setCard_no(data["card_no"])
        if "propertyright" in m:            
            house.setPropertyright(data["propertyright"])
        if "decorate_level" in m:            
            house.setDecorate_level(data["decorate_level"])
        if "Pay_commision" in m:            
            house.setPay_commision(data["Pay_commision"])
        if "rent_price" in m:            
            house.setRent_price(data["rent_price"])
        if "sale_unitprice" in m:            
            house.setSale_unitprice(data["sale_unitprice"])
        if "address" in m:            
            house.setAddress(data["address"])

        if "drawing_room" in m:            
            house.setDrawing_room(data["drawing_room"])
        if "pay_type" in m:            
            house.setPay_type(data["pay_type"])
        if "balcony" in m:            
            house.setBalcony(data["balcony"])
        if "commissiontype" in m:            
            house.setCommissiontype(data["commissiontype"])
        if "housestate" in m:            
            house.setHousestate(data["housestate"])

        if "owner_phone" in m:            
            house.setOwner_phone(data["owner_phone"])
        if "owner_orga_name" in m:            
            house.setOwner_orga_name(data["owner_orga_name"])
        if "build_year" in m:            
            house.setBuild_year(data["build_year"])
        if "layer" in m:            
            house.setLayer(data["layer"]) 
        if "commissiondate" in m:
            ltime = self.strippointer(data["commissiondate"]) 
            out = self.strtotime(ltime)               
            house.setCommissiondate(out)
            del ltime,out
        if "room" in m:            
            house.setRoom(data["room"])
        if "toilet" in m:            
            house.setToilet(data["toilet"])
        if "lastmodify_time" in m:
            ltime = self.strippointer(data["lastmodify_time"] )
            out = self.strtotime(ltime)            
            house.setLastmodify_time(out)
        if "bigarea" in m:            
#            house.setBigarea(data["bigarea"])
#        if "area" in m:            
#            house.setArea(data["area"])
            tmp = data["bigarea"]
            if isinstance(tmp,str):                                              
                tmp = self.backward_translate(tmp, bigarea_terms)                                        
            house.setBigarea(tmp)
            del tmp
            
        if "estate" in m:            
            house.setEstate(data["estate"])
        if "remark" in m:            
            house.setRemark(data["remark"])
        if "total_layer" in m:            
            house.setTotal_layer(data["total_layer"])       
            

        house.reindexObject()
        
        return msg
        
        
    